/**
 * @author 雷明浩
 * @date 2025/6/26 16:06
 */
public class IsBalanced_Solution {
    // 判断是不是平衡二叉树
    // https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=295&tqId=23250&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3DSQL%25E7%25AF%2587%26topicId%3D295
    public boolean IsBalanced_Solution (TreeNode pRoot) {
        // write code here
        if (pRoot == null) {
            return true;
        }
        if (!IsBalanced_Solution(pRoot.left)) {
            return false;
        }
        if (!IsBalanced_Solution(pRoot.right)) {
            return false;
        }
        int leftDeepth = deepth(pRoot.left);
        int rightDeepth = deepth(pRoot.right);
        if (Math.abs(leftDeepth - rightDeepth) > 1) {
            return false;
        }
        return true;
    }

    private int deepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDeepth = deepth(root.left);
        int rightDeepth = deepth(root.right);
        return Math.max(leftDeepth, rightDeepth) + 1;
    }
}